package cn.itsource.ymcc.utils.jwt;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.security.PublicKey;

/**
 * 用户上下文
 */
public class UserContext {
    
    //jwt token在请求头中的名称
    public static final String JWT_TOKEN_NAME = "U-TOKEN";

    /**
     * 获取当前登录用户
     *  一般在后端完成其他业务的时候，需要当前登录用户的id
     * @param jwtToken
     * @return
     */
    public static JSONObject getUser(String jwtToken){
        try {
            //利用JWT工具类解析token   私钥加密 公钥解密
            PublicKey publicKey = RsaUtils
                    .getPublicKey(FileCopyUtils
                            .copyToByteArray(UserContext.class.getClassLoader().getResourceAsStream("hrm_auth_rsa.pub")));
            Payload<PayloadData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, PayloadData.class);
            if(payload != null && payload.getUserInfo() != null ){
                return (JSONObject) payload.getUserInfo().getLogin();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前登录用户id
     * @param jwtToken
     * @return
     */
    public static Long getUserId(String jwtToken){
        try {
            JSONObject jsonObject = getUser(jwtToken);
            return jsonObject.getLong("id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static void main(String[] args) {
//        String token = "eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyIjoie1wibG9naW5cIjp7XCJhY2NvdW50Tm9uRXhwaXJlZFwiOnRydWUsXCJhY2NvdW50Tm9uTG9ja2VkXCI6dHJ1ZSxcImF2YXRhclwiOlwiaHR0cHM6Ly9pbWcyLmJhaWR1LmNvbS9pdC91PTMzMDk2NzYxMDAsNDMyMjY2NDM5JmZtPTI2JmZtdD1hdXRvJmdwPTAuanBnXCIsXCJjbGllbnRJZFwiOlwiYWRtaW5cIixcImNsaWVudFNlY3JldFwiOlwiMTIzXCIsXCJjcmVkZW50aWFsc05vbkV4cGlyZWRcIjp0cnVlLFwiZW5hYmxlZFwiOnRydWUsXCJpZFwiOjIsXCJwYXNzd29yZFwiOlwiJDJhJDEwJE5CYTltQzc3Rk9QVmRieWxiOXkyRnVIMHd3Z252WHp4alAwL0VIaU4wclR2cE9NNlV0NWNxXCIsXCJ0eXBlXCI6ZmFsc2UsXCJ1c2VybmFtZVwiOlwieWhwdGVzdFwifX0iLCJqdGkiOiJNV0k1WVdJd01XTXRNMk01WmkwME5EQXlMV0k0T1dNdFpHVXdaVFE0TWpReU56WTQiLCJleHAiOjE2OTQ1MDM4MDN9.JdgN2Woul2ODG9PEAOcWPoqxfgLCbZY4Po8Bz_7POMGJSC1PtJDDZqcc8IDh1yYeZ3YUNydQ6pZSbyfEyZ_B-V5aVcv2jjBzinW02jSUAB8iNbDJCibjI9idP9AKIHtS0JQL0VTirJAgDdJgbxTE5rZqNtVxa8ujSzPeyhsKwJSoTGdJlx8F4rvdTXIwJYL79Kdhq9f0yZ0a2lrVkwPkc-5yc97z1tizFoPMW4XklobiHDtuyLnHz7Awq5faRnkauK_Wvi0xLC9aU_pehAYwkkQLVWGJm5uqwj-GEjzeBwcmoZ5wqOqBBdJlg_LxuYxvhN0kQt9MZIWszAhaXZ_L3g";
//        System.out.println(getUser(token));
//        System.out.println(getUserId(token));
//    }

}